<template id="pdfToImage">
    <!-- pdf转图片 -->
    <div class="pdf-to-image">
        <i v-show="isLoading || isError" class="iconfont icon-tupian"><!--图片加载中--></i>
        <div v-show="!isLoading && !isError" class="image-container" id="pdf-container"></div>
    </div>
</template>

<script>
    var pdfToImage = {
        template: '#pdfToImage',
        props: {
            pdfPath: {type: String},
            scale: {type: Number, default: 1}
        },
        data() {
            return {
                isLoading: true,
                isError: false,
                pdfContainer: null
            };
        },
        methods: {
            async init() {
                this.isLoading = true;
                this.isError = false;

                // 清理原有图片
                while (this.pdfContainer?.firstChild) {
                    this.pdfContainer.removeChild(this.pdfContainer.firstChild);
                }
                if (!this.pdfPath) return;

                try {
                    const pdfUrl = this.pdfPath;
                    const scale = this.scale;

                    const pdf = await pdfjsLib.getDocument(pdfUrl).promise;
                    const numPages = pdf.numPages;

                    const pageCanvases = [];
                    let totalHeight = 0;
                    let maxWidth = 0;

                    const loadPagePromises = [];
                    for (let pageNumber = 1; pageNumber <= numPages; pageNumber++) {
                        const pagePromise = this.renderPageToCanvas(pdf, pageNumber, scale);
                        loadPagePromises.push(pagePromise);
                    }

                    const renderedPages = await Promise.all(loadPagePromises);
                    renderedPages.forEach((canvas) => {
                        pageCanvases.push(canvas);
                        totalHeight += canvas.height;
                        maxWidth = Math.max(maxWidth, canvas.width);
                    });

                    const combinedCanvas = this.combineCanvases(pageCanvases, totalHeight, maxWidth);

                    const img = new Image();
                    // 图片像素比调整
                    // img.src = combinedCanvas.toDataURL("image/png");
                    img.src = combinedCanvas.toDataURL("image/jpg", this.scale);

                    img.onload = () => {
                        this.pdfContainer.appendChild(img);
                        this.isLoading = false;
                    };
                    img.onerror = () => {
                        this.isError = true;
                    };

                } catch (error) {
                    // console.error('PDF 转图片过程中出现错误:', error);
                    this.isLoading = false;
                }
            },
            async renderPageToCanvas(pdf, pageNumber, scale) {
                const page = await pdf.getPage(pageNumber);
                const viewport = page.getViewport({scale: scale});

                const canvas = document.createElement("canvas");
                const context = canvas.getContext("2d");
                canvas.height = viewport.height;
                canvas.width = viewport.width;

                // 设备像素比调整
                /*if (this.scale > 1) {
                    const devicePixelRatio = window.devicePixelRatio || 1;
                    canvas.style.width = `${canvas.width}px`;
                    canvas.style.height = `${canvas.height}px`;
                    canvas.width = canvas.width * devicePixelRatio;
                    canvas.height = canvas.height * devicePixelRatio;
                    context.scale(devicePixelRatio, devicePixelRatio);
                }*/
                const renderContext = {
                    canvasContext: context,
                    viewport: viewport
                };

                await page.render(renderContext).promise;
                return canvas;
            },
            combineCanvases(pageCanvases, totalHeight, maxWidth) {
                const combinedCanvas = document.createElement("canvas");
                const combinedContext = combinedCanvas.getContext("2d");
                combinedCanvas.height = totalHeight;
                combinedCanvas.width = maxWidth;

                let currentY = 0;
                for (let i = 0; i < pageCanvases.length; i++) {
                    const pageCanvas = pageCanvases[i];
                    combinedContext.drawImage(pageCanvas, 0, currentY);
                    currentY += pageCanvas.height;
                }

                return combinedCanvas;
            }
        },
        mounted() {
            this.pdfContainer = document.getElementById("pdf-container");
            Promise.all([
                wzbRequire.require("/vue-page/v2/resources/js/plug-in/pdf/pdf.worker.min.js"),
                wzbRequire.require("/vue-page/v2/resources/js/plug-in/pdf/pdf.min.js"),
            ]).then(() => {
                pdfjsLib.GlobalWorkerOptions.workerSrc = "/vue-page/v2/resources/js/plug-in/pdf/pdf.worker.min.js";
                this.init();
            }).catch((error) => {
                console.error('加载 PDF 相关脚本时出现错误:', error);
            });
        },
        watch: {
            pdfPath(newValue) {
                if (newValue) this.init();
            }
        }
    };
</script>

<style>
    .pdf-to-image {
        width: 100%;
        height: 100%;
    }

    .pdf-to-image > i {
        height: 100%;
        width: 100%;
        background: #f7f7f8;
        overflow: hidden;
        color: gray;
        font-size: 60px;
        display: flex;
        align-content: center;
        align-items: center;
        justify-content: center;
    }

    .pdf-to-image .image-container {
        width: 100%;
        height: 100%;
        position: relative;
    }

    .pdf-to-image .image-container > img {
        width: 100%;
        object-fit: contain;
        position: absolute;
        top: 0;
        left: 0;
    }
</style>